package com.probiz.estoresa.sales.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.model.sales.GiftCertificate;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.sales.model.GiftCertificateSearchCriteria;
import com.probiz.estore.sales.service.GiftCertificateManager;

/**
 * 后台礼券controller
 * 
 * 
 */
public class GiftCertificateController extends GenericStoreAdminController<GiftCertificate> {
	private GiftCertificateManager giftCertificateManager ;

	public void setGiftCertificateManager(GiftCertificateManager giftCertificateManager) {
		this.giftCertificateManager = giftCertificateManager;
	}

	protected void initController() throws Exception {
		mgr = giftCertificateManager;
	}

	@Override
	protected Map<String, String> getSortMap() {
		Map<String, String> sortMap = new HashMap<String, String>();
		sortMap.put("0", "giftCertificateNo");
		sortMap.put("1", "remainedAmt");
		sortMap.put("2", "giftCertAmt");
		sortMap.put("3", "orderNo");
		sortMap.put("4", "orderNoInUse");
		sortMap.put("5", "createTime");
		sortMap.put("6", "expireTime");
		return sortMap;
	}

	@Override
	protected String getEntityName(GiftCertificate entity) {
		return entity.getGiftCertificateNo();
	}

	public ModelAndView search(HttpServletRequest request, HttpServletResponse response) {
		SearchCriteria sc = createSearchCriteria(request);
		List<GiftCertificate> results;
		GiftCertificateSearchCriteria giftCertificateSearchCriteria = new GiftCertificateSearchCriteria();
		bindOnly(request, giftCertificateSearchCriteria);
		results = giftCertificateManager.searchGiftCertificates(sc, giftCertificateSearchCriteria);
		request.setAttribute("giftCertificateSearchCriteria", giftCertificateSearchCriteria);
		return getModelAndView(listView, listModelName, results);
	}


	public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		GiftCertificate entity = formBackingObject(request);
		entity.setIsSentByEmail(Constants.FLAG_TRUE);

		BindException errors = null;
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				entity.setStatus(GiftCertificate.STATUS_ACTIVE);
				if (null == entity.getGiftCertificateId()) {
					giftCertificateManager.createGiftCertificate4Admin(entity);
				}
				String msgKey = (isEntityNew(request)) ? "common.added" : "common.updated";
				String message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
				saveMessage(request, message);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		ModelAndView mav;
		if (errors.hasErrors()) {
			mav = showForm(request, errors);
		} else if (successView != null) {
			mav = getModelAndView(successView, errors.getModel());
		} else {
			mav = getRedirectToActionView("edit", ((BaseObject) entity).getId().toString());
		}
		return mav;
	}

	public ModelAndView sendEmail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		GiftCertificate entity = formBackingObject(request);

		boolean sended = false;
		try {
			giftCertificateManager.sendGiftCertificate(entity, null);
			sended = true;

			String msgKey = "giftCertificate.sendEmail.success";
			String message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
			saveMessage(request, message);
		} catch (Exception e) {
			logger.error(e);
			String msgKey = "giftCertificate.sendEmail.error";
			String message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
			saveErrorMessage(request, message);
		}

		ModelAndView mav = getRedirectToActionView("edit", ((BaseObject) entity).getId().toString());
		return mav;
	}

	public ModelAndView saveAndSendEmail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		GiftCertificate entity = formBackingObject(request);
		entity.setIsSentByEmail(Constants.FLAG_TRUE);

		BindException errors = null;
		boolean sended = false;
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				entity.setStatus(GiftCertificate.STATUS_ACTIVE);
				if (null == entity.getGiftCertificateId()) {
					giftCertificateManager.createGiftCertificate4Admin(entity);
				}
				String msgKey = (isEntityNew(request)) ? "common.added" : "common.updated";
				String message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
				saveMessage(request, message);
				try {
					giftCertificateManager.sendGiftCertificate(entity, null);
					sended = true;

					msgKey = "giftCertificate.sendEmail.success";
					message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
					saveMessage(request, message);
				} catch (Exception e) {
					logger.error(e);
					msgKey = "giftCertificate.sendEmail.error";
					message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
					saveErrorMessage(request, message);
				}
			}

		} catch (Exception e) {
			logger.error(e);
		}

		ModelAndView mav;
		if (errors.hasErrors()) {
			mav = showForm(request, errors);
		} else if (successView != null) {
			mav = getModelAndView(successView, errors.getModel());
		} else {
			mav = getRedirectToActionView("edit", ((BaseObject) entity).getId().toString());
		}
		return mav;
	}

	public ModelAndView active(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		GiftCertificate entity = formBackingObject(request);

		try {
			entity.setStatus(GiftCertificate.STATUS_ACTIVE);
			mgr.save(entity);
			String msgKey = (isEntityNew(request)) ? "common.added" : "common.updated";
			String message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
			saveMessage(request, message);

		} catch (ApplicationException e) {
			e.printStackTrace();
		}

		ModelAndView mav = getRedirectToActionView("edit", ((BaseObject) entity).getId().toString());
		return mav;
	}

	public ModelAndView forbit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		GiftCertificate entity = formBackingObject(request);

		try {
			entity.setStatus(GiftCertificate.STATUS_UNACTIVE);
			mgr.save(entity);
			String msgKey = (isEntityNew(request)) ? "common.added" : "common.updated";
			String message = getMessage(msgKey, new Object[] { getEntityTypeMessage(), getEntityName(entity) });
			saveMessage(request, message);

		} catch (ApplicationException e) {
			e.printStackTrace();
		}

		ModelAndView mav = getRedirectToActionView("edit", ((BaseObject) entity).getId().toString());
		return mav;
	}

}
